package minidb.parse.exps;

import java_cup.runtime.SyntexException;
import minidb.parse.*;

public class UserExp extends SQLExp
{
	public static enum UserType {ADD,DELETE,SET};
	
	private UserType uType;
	private String userName;
	private String password;
	
	public UserExp(UserType ut,String name,String pwd)
	{
		this.uType=ut;
		this.userName=name;
		this.password=pwd;
	}
	
	public Boolean HasAuthority(String cur_name)
	{
		if(cur_name.equals("system") || cur_name.equals(this.userName))
			return true;
		else 
			return false;
	}
	
	public SQLExp Transform()
	{
		String sql=null;
		switch(this.uType)
		{
			case ADD:
				sql=String.format("insert into SystemUser (username,password) values('%s','%s')",this.userName,this.password);
				break;
			case DELETE:
				sql=String.format("delete from SystemUser where SystemUser.username='%s'", this.userName);
				break;
			case SET:
				sql=String.format("update SystemUser set password='%s' where SystemUser.username='%s'",this.password,this.userName);
				break;
		}
		
		Parse p = new Parse(sql, false);
		SQLExp exp;
		try
		{
			exp = p.ExecParse();
		} catch (SyntexException e)
		{
			throw new RuntimeException("UserExp.Transform():Transform failed");
		}
		
		return exp;
	}
	
	
	@Override
	public String Print()
	{
		return "USER "+this.uType.name()+" "+this.userName+(this.password!=null ? this.password : "")+"\n";
	}

}
